import { defineStore } from "pinia";
import { store } from "@/store";
import { useTagsViewStore, TagView } from "@/store/modules/tagsView";
import { getExpInfoApi } from "@/api/experiment";

// 导航栏
const tagsViewStore = useTagsViewStore();
export const useCorrectStore = defineStore("correct", () => {
  // state 变量
  // 任务ID
  const experimentId = ref();
  // 课程名称
  const taskName = ref("");
  // 主教老师
  const leaderName = ref("");

  // actions
  // 保存id信息
  function correctTask(id: number) {
    return new Promise<void>((resolve, reject) => {
      experimentId.value = id;
      resolve();
    });
  }
  // 获取课程信息
  function getExpInfo(id: number) {
    return new Promise<void>((resolve, reject) => {
      getExpInfoApi(id)
        .then(({ data }) => {
          if (!data) {
            return reject("Verification failed, please Login again.");
          }
          experimentId.value = id;
          taskName.value = data.name!;
          leaderName.value = data.leaderName!;
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 重置课程信息
  function resetCorrect() {
    experimentId.value = null;
    taskName.value = "";
    leaderName.value = "";
  }

  // 重置课程信息
  function removeCache() {
    return new Promise<void>((resolve, reject) => {
      const views = tagsViewStore.visitedViews.filter((view: TagView) => {
        return view.meta?.layout === "CorrectLayout";
      });
      tagsViewStore
        .delViews(views)
        .then((res: any) => {
          resolve();
        })
        .catch(() => {
          reject();
        });
    });
  }

  return {
    experimentId,
    taskName,
    leaderName,
    correctTask,
    getExpInfo,
    resetCorrect,
    removeCache,
  };
});

// 非setup
export function useCorrectStoreHook() {
  return useCorrectStore(store);
}
